<template>
  <div class="signing-page base-table-page" v-if='getActState($rootsList.usualRoots.LIST)'>
    <div class="search-box">
      <div class="left">
        <div class="first-search" v-show="getSelectionLen === 0">
          <FirstFilter :cache-key="cacheTableKey" ref="filterSearchDialog" :tableType="filterType"
            @tableLoadFromFilter="tableLoadFromFilter" @setFirstSearch="setFirstSearch"
            :all-list="allFilterSearchList" :className.sync="className"></FirstFilter>
        </div>
        <div class="selected-box" v-show="getSelectionLen > 0">
          <TableSelectOperate :getSelectionLen="getSelectionLen" :list="operateList"
            @handleClose="closeSelected"></TableSelectOperate>
        </div>
      </div>
      <div class="right">
        <div class="second-search">
          <SecondFilter @setSecondSearch="setSecondSearch" :list="searchFormData"></SecondFilter>
        </div>
        <div class="line"></div>
        <PrimaryButton text="新建签约" @handleClick="handleAdd" @command="handleCommand"
          :list="btnList"></PrimaryButton>
      </div>
    </div>
    <STable @selectionChange="selectionChange" v-if="loadRef" :show-filter="true" :query="query"
      :table-cache-key="cacheTableKey" @load="tableLoad" @getTableRef="getTableRef"
      @handleShowField="handleShowField" @rowClick="handleRowClick"
      :type="tableItemType.tabType.selection" ref="stable" class="s_table icon-table"
      :column="dynamicColumn" :request="request"
      :handleField="getActState(this.$rootsList.usualRoots.LIST_CONFIG)"
      :delay-request-flag="delayTableRequestFlag" @tableHeaderFilter="tableHeaderFilter">
      <template v-slot:tableColumnBefore="slotData">
        <CustomTableOrder :tableInfo="slotData.tableInfo" :have-flow="true" @clickFlow="clickFlow">
        </CustomTableOrder>
      </template>
      <template slot="tableTotal" v-if="tableTotalList.length > 0">
        <TableTotal :list="tableTotalList" :tableType="filterType"></TableTotal>
      </template>
    </STable>
    <DetailContainer :visible.sync="detailVisible" size="1005px" :data="detailData"
      :disabled="processStatus === businessFlowStatusConfig.flowProcessing"
      :operation="operationList">
      <div slot='approval_status' class="approval_status">
        <img v-show="processStatus === businessFlowStatusConfig.flowProcessing" :src="reviewImg"
          alt="" />
      </div>
      <div slot="operate" class="operates">
        <!-- 只有数据负责人才有共享按钮 -->
        <el-button :disabled="detailVisible && detailData.detail.shareFlag === '1'"
          v-if="detailVisible && userId === detailData.detail.signFollowUserId" type="primary"
          class="operate-btn" size="mini" @click="handleShare">共享</el-button>
        <el-button
          :disabled="(processStatus === businessFlowStatusConfig.flowProcessing) || (detailVisible && detailData.detail.shareFlag === '1')"
          type="primary" class="operate-btn" size="mini" @click="incoming"
          v-permission="$rootsList.customerManageRoots.INTO">进件</el-button>
        <el-button
          :disabled="(processStatus === businessFlowStatusConfig.flowProcessing) || (detailVisible && detailData.detail.shareFlag === '1')"
          type="primary" class="operate-btn" size="mini" @click="transfer"
          v-permission="$rootsList.usualRoots.TRANSFER">移交</el-button>
      </div>
      <template slot="formBlock" slot-scope="{activeName}">
        <!--详细信息-->
        <CustomFormDetail v-if="activeName === 0" key='singing' :data="addSigningData"
          :tableType="filterType" :sub-table-data="subTableData" :system-info-list="systemInfoList">
        </CustomFormDetail>
        <!--成本项-->
        <div class="cost-item-box" v-if="activeName===1" :style="{padding:'0 16px;'}">
          <div class="box">
            <!-- 成本 -->
            <div v-if="!organizationInfo.cpsFlag||channel_current==0">
              <div class="add-cost" @click="addCost('')" :class="{'noClick': detailData.detail.shareFlag === '1'}"
                v-if="processStatus !== businessFlowStatusConfig.flowProcessing && (!costItemData || (costItemData && costItemData.hasCost === 0))">
                <em>+</em>添加成本信息
              </div>
              <div class="contact-list" v-if="costItemData && costItemData.hasCost === 1">
                <div class="contact-item">
                  <i class="el-icon-edit-outline icon-edit" :class="{'noClick': detailData.detail.shareFlag === '1'}"
                    v-show="processStatus !== businessFlowStatusConfig.flowProcessing"
                    @click="editCost(costItemData)"></i>
                  <el-row :gutter="20" v-if="costItemData.costList && costItemData.costList.length">
                    <el-col class="col-item" :span="12" v-for="(i, idx) in costItemData.costList"
                      :key="idx">
                      <label class="item-label">{{i.costTerm}}:</label>
                      <p class="content">{{i.costAmount}}</p>
                    </el-col>
                  </el-row>
                  <el-row :gutter="20">
                    <el-col :span="24" class="col-item">
                      <label class="item-label">备注:</label>
                      <p class="content">{{costItemData.remark || '-'}}</p>
                    </el-col>
                  </el-row>
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- 基本资料 -->
        <template v-if='activeName===2'>
          <!--          <CustomFormDetail key='basic' :data="customerData" :tableType="baseFilterType"-->
          <!--            :sub-table-data="subTableData" :system-info-list="customerSystemInfo">-->
          <!--          </CustomFormDetail>-->
          <template v-if="customerBasicData.cstSource === infoFlowCustomerType">
            <InfoFlowCustomer :tableType="baseFilterType" ref="customForm" :data="customerBasicData"
              :disabled="true" :systemInfoList="customerSystemInfo" :sub-table-data="subTableData">
            </InfoFlowCustomer>
          </template>
          <template v-else>
            <CustomFormDetail key='basic' :data="customerData" :tableType="baseFilterType"
              :sub-table-data="subTableData" :system-info-list="customerSystemInfo">
            </CustomFormDetail>
          </template>
        </template>
        <!-- 复印件 -->
        <template v-if='activeName===3'>
          <CustomerProfile :data="customerData" :pageDisabled="detailDisabled"></CustomerProfile>
        </template>
        <!-- 还款计划 -->
        <RepaymentPlan key='repay' :data='planData' v-if='activeName===4'
          :disabled='detailDisabled'>
        </RepaymentPlan>
      </template>
    </DetailContainer>
    <!--添加签约-->
    <AddCustomForm :visible.sync="visible" :table-type="filterType" :is-edit="signIsEdit"
      :sub-table-data="subTableData" :needInitRequest="needInitRequest" :data="addSigningData"
      @success="signSure"></AddCustomForm>
    <!--添加进件-->
    <AddCustomForm :visible.sync="AddIncomingVisible" :is-edit="false"
      :needInitRequest="needInitRequestIncoming" :table-type="formFieldConfigValue.incoming"
      :data="addIncomingData" :have-customer="true" :customer-data="customerData"
      @success="addIncomingSuccess">
    </AddCustomForm>
    <!--显示字段的配置弹窗-->
    <ShowFieldsDialog :visible.sync="showFieldVisible" :column="fieldList"
      :cacheTableKey="cacheTableKey" @sure="handleShowFieldSure"></ShowFieldsDialog>
    <!--分配弹窗-->
    <PeopleSelect :visible.sync="transferVisible" :business-type="businessType"
      @sure="transferSure">
    </PeopleSelect>
    <!--删除弹窗-->
    <DeleteDialog :visible.sync="deleteVisible"
      :main-text="getSelectionLen > 1&&!isClickRow ? `是否将选中的${getSelectionLen}个签约删除？` : `是否将该签约删除？`"
      :sub-text="`删除后数据无法恢复。`" @sure="deleteSure"></DeleteDialog>
    <!--成本项-->
    <CostDialog :visible.sync="costVisible" :data="costItemData" @handleSure="costSure">
    </CostDialog>
    <!-- 添加渠道成本项 -->
    <ChanelCostDialog :visible.sync="chanleCostVisible" :data.sync="chanelCostItemDta"
      @handleSure="channleSure">
    </ChanelCostDialog>
    <!--流程详情页面-->
    <FlowDetail :visible.sync="flowDetailVisible" :data="flowDetailData" @success="flowSuccess">
    </FlowDetail>
    <!-- 共享 -->
    <ShareDataDialog :visible.sync="shareVisible" :isShareDataList="isShareDataList"
      @sure="handleShareSure"></ShareDataDialog>
  </div>
</template>

<script>
import TableTotal from '@/components/business/tableTotal/index';
import FlowDetail from '@/components/business/flowDetail/index';
import CustomTableOrder from '@/components/business/customTableOrder/index';
import CustomerProfile from '@/views/customerManage/components/customerProfile';
import RepaymentPlan from '@/views/customerManage/components/repaymentPlan';
import CustomFormDetail from '@/components/custom/form/detail.vueBox';
import AddCustomForm from '@/components/custom/form/index';
import CostDialog from './costDialog';
import PeopleSelect from '@/components/business/singlePeopleSelect';
import DeleteDialog from '@/components/business/deleteDialog';
import SecondFilter from '@/components/business/filter/second';
import PrimaryButton from '@/components/business/button/primary';
import STable from '@/components/restructure/table';
import AddSigning from './addSigning/index';
import ShowFieldsDialog from '@/components/business/showFieldsDialog';
import reviewImg from '@/assets/under_review.png';
import { formItemType, tableItemType } from '@/utils/config';
import ChanelCostDialog from './chanelCostDialog';
import { mapGetters } from 'vuex';
import {
  delSigning,
  getSigningList,
  shopSaasSignExportExcel,
  transferSigning,
  operateSignCost,
  getSignCostApi,
  addSigning, updateSigning, addIncoming, updateIncoming, updateChannelCost, enterpriseCanViewOrder
} from '@/api/signingIncoming';
import { businessFlowStatusConfig } from '@/enum/flowManage';
import { sincerityStatusList, loanCategoryList, repaymentTypeList } from '@/enum/signingIncoming';
import filterSearchMixin from '@/mixins/filterSearch';
import commonField from '@/mixins/commonField';
import {
  businessTypeConfig,
  cacheTableKeyConfig,
  checkUserPermissionTypeConfig,
  formFieldConfigValue
} from '@/enum/systemManage';
import commonTable from '@/mixins/commonTable';
import InfoFlowCustomer from '@/components/custom/form/infoFlowCustomer.vueBox';
import { selectClientUsers, getCustomerDetailById, polymerizationTableDataSign, getInfoFlowOrderById } from '@/api/customerManage';
import { canModifyOrder, getDepartmentListApi, getOrganInfoApi } from '@/api/systemManage';
import { getCapitalProductListNoPage } from '@/api/product';
import DetailContainer from '@/components/business/detailPage/detailContainer';
import { getActState, getToApply } from '@/utils/roots';
import signIncomingList from '@/mixins/signIncomingList';
import { getSignDetailApi, getSubTableDataByBusiness, shareDataList, shareDataSave } from '@/api/perDefineObject';
import { signSystemInfo, customerSystemInfo } from '@/enum/configSystemInfo';
import { getFlowDetailDataByBusiness } from '@/api/flowManage';
import { computedCurrentPageTotal } from '@/enum/business';
import exportFieldDialog from '@/components/business/exportFieldDialog';
import { infoFlowCustomerType } from '@/enum/customerManage';
import ShareDataDialog from '@/components/business/shareDataDialog';

export default {
  components: {
    STable,
    AddSigning,
    ShowFieldsDialog,
    DeleteDialog,
    SecondFilter,
    PrimaryButton,
    DetailContainer,
    ChanelCostDialog,
    PeopleSelect,
    CostDialog,
    AddCustomForm,
    CustomFormDetail,
    CustomerProfile,
    RepaymentPlan,
    FlowDetail,
    CustomTableOrder,
    TableTotal,
    InfoFlowCustomer,
    ShareDataDialog
  },
  mixins: [filterSearchMixin, commonField, commonTable, signIncomingList],
  props: {
  },
  mounted () {
    // 获取当前详情里面是否禁用状态
    this.detailDisabled = !getActState(this.$rootsList.usualRoots.EDIT);
    // 获取当前机构状态
    this.getOrganId();
    // 数据指标埋点
    this.$dataIndicatorBuryingPoint(22);
    /* 获取成员类表 */
    selectClientUsers().then(msg => {
      if (!this.basics.isNull(msg)) {
        this.subUsers = msg;
      }
    });
    /* 获取全部产品 */
    getCapitalProductListNoPage().then(msg => {
      this.selectProductList = msg;
    });
    /* 获取部门列表 */
    getDepartmentListApi().then((res) => {
      this.departmentList = res || [];
    });
    this.getCustomFields(); // 获取自定义字段
  },
  data () {
    return {
      baseFilterType: formFieldConfigValue.customer,
      planData: {}, // 计划还款数据
      customerSystemInfo,
      needInitRequest: {
        tableType: 60,
        fieldCode: 'contractNum' // 签约id的fieldCode
      },
      needInitRequestIncoming: {
        tableType: 70,
        fieldCode: 'intoId' // 进件id的fieldCode
      },
      subTableData: [], // 所有子表的数据
      channel_current: 0,
      getActState,
      reviewImg,
      businessFlowStatusConfig,
      customerData: {},
      cpsFlag: true,
      formFieldConfigValue,
      systemInfoList: signSystemInfo,
      channelList: ['渠道成本', '成本项'],
      signId: '', // 签约Id
      costItemData: null, // 成本列表每一项数据
      chanelCostItemDta: null, // 渠道成本数据
      costVisible: false, // 成本弹窗显示控制
      chanleCostVisible: false, // 渠道成本弹窗
      costType: 'add', // 成本项添加类型
      businessType: businessTypeConfig.sign,
      tableType: formFieldConfigValue.sign,
      isClickRow: true,
      repaymentTypeList,
      loanCategoryList,
      detailVisible: false,
      detailData: {},
      processStatus: '', // 审核状态
      detailDisabled: false, // 详情里面是否禁用
      operationList: [
        {
          label: '编辑',
          value: 0,
          show: true,
          fn: (params) => {
            if (!getActState(this.$rootsList.usualRoots.EDIT)) {
              this.$message.error('暂无权限');
              return;
            }
            canModifyOrder({ shopOrderId: params.id, type: checkUserPermissionTypeConfig.normalLoan }).then(res => {
              if (typeof res === 'boolean' && res) {
                getSignDetailApi({
                  id: params.id
                }).then(res => {
                  this.signIsEdit = true;
                  this.addSigningData = res || {};
                  this.visible = true;
                });
              } else {
                this.$message.error('暂无权限');
              }
            });
          }
        },
        {
          label: '删除',
          value: 1,
          show: true,
          fn: (params) => {
            if (!getActState(this.$rootsList.usualRoots.DELETE)) {
              this.$message.error('暂无权限');
              return;
            }
            canModifyOrder({ shopOrderId: params.id, type: checkUserPermissionTypeConfig.normalLoan }).then(res => {
              if (typeof res === 'boolean' && res) {
                this.isClickRow = true;
                this.deleteVisible = true;
              } else {
                this.$message.error('暂无权限');
              }
            });
          }
        }
      ],
      searchBoxDisabled: false, // 编辑签约时的客户不可搜索,变更
      subUsers: [],
      selectProductList: [],
      departmentList: [],
      btnList: [ // 按钮列表
        {
          value: 2,
          label: '导出',
          clickFn: (vm) => {
            if (!getActState(this.$rootsList.usualRoots.EXPORT)) {
              this.$message.error('暂无权限');
              return;
            }
            exportFieldDialog({
              tableType: vm.filterType
            }).then((exportExcludeIdStr) => {
              vm.isClickRow = false;
              const query = { ...this.query, exportExcludeIdStr };
              const url = this.exportExcel;
              vm.handleExport(url, query);
            });
          }
        }
      ],
      operateList: [ // 操作列表
        {
          value: 1,
          label: '移交',
          icon: 'icon-zhuanfa',
          clickFn: (vm = this) => {
            if (!getActState(this.$rootsList.usualRoots.TRANSFER)) {
              this.$message.error('暂无权限');
              return;
            }
            vm.isClickRow = false;
            vm.transferVisible = true;
          }
        },
        {
          value: 4,
          label: '导出',
          icon: 'icon-daochu',
          clickFn: (vm = this) => {
            if (!getActState(this.$rootsList.usualRoots.EXPORT)) {
              this.$message.error('暂无权限');
              return;
            }
            exportFieldDialog({
              tableType: vm.filterType
            }).then((exportExcludeIdStr) => {
              vm.isClickRow = false;
              const url = this.exportExcel;
              const queryData = {
                ids: vm.getSelectionIds.join(','),
                exportExcludeIdStr
              };
              vm.handleExport(url, queryData);
            });
          }
        },
        {
          value: 5,
          label: '删除',
          icon: 'el-icon-delete',
          clickFn: (vm = this) => {
            if (!getActState(this.$rootsList.usualRoots.DELETE)) {
              this.$message.error('暂无权限');
              return;
            }
            vm.isClickRow = false;
            vm.deleteVisible = true;
          }
        }
      ],
      deleteVisible: false, // 删除弹窗
      transferVisible: false, // 派发弹窗
      cacheTableKey: cacheTableKeyConfig.sign,
      filterType: formFieldConfigValue.sign,
      AddIncomingVisible: false,
      addSigningData: {},
      addIncomingData: {},
      tableData: [],
      signIsEdit: false, // 签约是否是编辑
      loadRef: false,
      exportExcel: shopSaasSignExportExcel,
      tableItemType,
      // 新增预约弹窗的显示
      visible: false,
      // 表格列表项
      column: [
        {
          key: 'id',
          title: '签约ID',
          minWidth: '90px'
        },
        {
          key: 'name',
          title: '姓名',
          minWidth: '90px'
        },
        {
          key: 'phone',
          title: '联系电话',
          minWidth: '120px'
        },
        {
          key: 'followUserName',
          title: '负责人',
          minWidth: '120px'
        },
        {
          key: 'orderFollowUserName',
          title: '客户归属',
          minWidth: '120px'
        },
        {
          key: 'followUserDep',
          title: '所属部门',
          minWidth: '120px'
        },
        {
          key: 'contractNum',
          title: '合同号',
          minWidth: '120px'
        },
        {
          key: 'productName',
          title: '贷款产品',
          minWidth: '150px'
        },
        {
          key: 'loanMoney',
          title: '贷款金额',
          minWidth: '120px',
          render: (h, { data }) => {
            return h('span', data.row.loanMoney);
          }
        },
        {
          key: 'loanTerm',
          title: '贷款期限',
          minWidth: '120px',
          render: (h, { data }) => {
            return h('span', data.row.loanTerm);
          }
        },
        {
          key: 'updateUserName',
          title: '最新修改人',
          minWidth: '120px'
        },
        {
          key: 'updateTime',
          title: '最新更新时间',
          minWidth: '150px',
          tableView: tableItemType.tableView.date
        },
        {
          key: 'serviceRate',
          title: '服务费',
          minWidth: '90px'
        },
        {
          key: 'sincerityGold',
          title: '诚意金',
          minWidth: '90px',
          render: (h, { data }) => {
            const row = data.row;
            return h('span', !this.basics.isNull(row.sincerityGold) ? row.sincerityGold.toFixed(2) : '-');
          }
        },
        {
          key: 'sincerityType',
          title: '诚意金状态',
          minWidth: '90px',
          list: sincerityStatusList,
          tableView: tableItemType.tableView.text
        }
        // {
        //   key: 'loanMoney',
        //   title: '贷款金额',
        //   minWidth: '150px',
        //   tableView: tableItemType.tableView.text
        // }
        // {
        //   key: 'sincerityAccept',
        //   title: '诚意金收款方式'
        // }
      ],
      // 表格的请求
      request: {
        getListUrl: (data) => getSigningList(data).then(msg => {
          this.pageNum = data.pageNum;
          this.tableData = msg.datas || [];
          // 优化项(减少接口请求): 当只是排序的变化请求时,不需要再请求总条数的合计,只需重新计算本页的合计就行
          if (data.notRequestTotal) {
            this.tableTotalList = computedCurrentPageTotal(this.tableTotalList, msg.datas || []);
          } else {
            this.dealTableTotal({ ...data }, msg.datas || []);
          }
          return msg;
        })
      },
      className: '',
      flowDetailData: {}, // 流程详情数据
      flowDetailVisible: false, // 流程详情弹窗
      tableTotalList: [], // 表格合计列表
      infoFlowCustomerType,
      customerBasicData: {}, // 信息流直推的基本资料
      shareVisible: false,
      isShareDataList: []
    };
  },
  computed: {
    transferList () {
      return this.subUsers;
    },
    // 搜索条件
    searchFormData () {
      return [
        {
          key: 'name',
          title: '客户姓名',
          type: formItemType.input,
          options: {
            placeholder: '客户姓名'
          }
        },
        {
          key: 'followUserId',
          title: '负责人',
          type: formItemType.select,
          list: this.subUsers,
          listFormat: {
            value: 'id',
            label: 'realName'
          },
          options: {
            placeholder: '负责人'
          }
        },
        {
          key: 'productId',
          title: '贷款产品',
          type: formItemType.select,
          list: this.selectProductList,
          listFormat: {
            value: 'id',
            label: 'productName'
          }
        },
        {
          key: 'orderFollowUserId',
          title: '客户归属',
          type: formItemType.select,
          list: this.subUsers,
          listFormat: {
            value: 'id',
            label: 'realName'
          }
        },
        {
          key: 'followUserDepId',
          title: '所属部门',
          type: formItemType.customCascader,
          list: this.departmentList
        },
        {
          key: 'createUserName',
          title: '创建人',
          type: formItemType.input,
          options: {
            placeholder: '创建人'
          }
        },
        {
          key: 'date',
          title: '创建时间',
          type: formItemType.rangeDatePicker,
          childKey: ['startTime', 'endTime'],
          options: {
            placeholder: '创建时间'
          }
        }
      ];
    },
    ...mapGetters(['organizationInfo']),
    userId () { // 用户ID
      return this.$store.state.user.userInfo.id;
    }
  },
  methods: {
    // 获取成本列表
    getCostList (signId) { // 进入详情页面时才调用,
      getSignCostApi({ signId }).then(res => {
        this.costItemData = res || null;
      });
    },
    // 添加编辑成本项确认
    costSure (data) {
      const postData = {
        signId: this.signId || this.detailData.detail.id,
        costJsonStr: JSON.stringify(data.list),
        remark: data.remark
      };
      operateSignCost(postData).then(res => {
        this.$message.success('操作成功');
        this.costVisible = false;
        this.reloadTable();
        this.getCostList(this.detailData.detail.id);
        this.signId = '';
      });
    },
    // 渠道成本编辑确认
    channleSure (data) {
      updateChannelCost(data).then(res => {
        this.$message({
          message: '修改成功',
          type: 'success'
        });
        this.chanleCostVisible = false;
        this.chanelCostItemDta = { ...data };
        this.reloadTable();
      });
    },
    // 编辑成本项
    editCost (data) {
      // 如果处于流程审批中,则不能进行操作
      if (this.processStatus === businessFlowStatusConfig.flowProcessing) {
        return;
      }
      this.costType = 'edit';
      this.costItemData = { ...data };
      this.costVisible = true;
    },
    // 添加成本项
    addCost (signId = '') {
      // 如果处于流程审批中,则不能进行操作
      if (this.processStatus === businessFlowStatusConfig.flowProcessing) {
        return;
      }
      this.costType = 'add';
      this.signId = signId;
      this.costItemData = null;
      this.costVisible = true;
    },
    addCostCps () {
      // 如果处于流程审批中,则不能进行操作
      if (this.processStatus === businessFlowStatusConfig.flowProcessing) {
        return;
      }
      this.chanleCostVisible = true;
    },
    // 移交
    transfer () {
      this.transferVisible = true;
    },
    // 进件(新增进件)
    incoming () {
      getCustomerDetailById({ id: this.detailData.detail.flowOrderId }).then(customerData => {
        if (customerData.followUserId) { // followUserId===0 为公海用户
          canModifyOrder({ shopOrderId: this.detailData.detail.id, type: checkUserPermissionTypeConfig.normalLoan }).then(res => {
            if (typeof res === 'boolean' && res) {
              this.addIncomingData = customerData;
              // this.addIncomingData.productId = ''; // 点击进件 表示新建进件，清空产品ID
              // this.addIncomingData.remark = '';
              this.AddIncomingVisible = true;
            } else {
              this.$message.error('无编辑权限');
            }
          });
        } else {
          this.$message.error('客户已被移入公海,请先领取');
        }
      });
    },
    // 确认新增,编辑签约
    signSure (postData, { originData }) {
      const successFn = () => {
        this.$message.success('操作成功');
        this.visible = false;
        this.detailVisible = false;
        // this.AddIncomingVisible = false;
        this.reloadTable();
      };
      if (this.signIsEdit) {
        updateSigning({
          id: originData.id,
          ...postData
        }).then(res => {
          successFn();
        });
      } else {
        addSigning(postData).then(res => {
          successFn();
        });
      }
    },
    // 确认新增进件
    addIncomingSuccess (postData, { originData }) {
      const successFn = () => {
        this.$message.success('操作成功');
        // this.detailVisible = false;
        this.AddIncomingVisible = false;
        this.reloadTable();
      };
      if (this.signIsEdit) {
        updateIncoming({
          id: originData.id,
          ...postData
        }).then(res => {
          successFn();
        });
      } else {
        addIncoming(postData).then(res => {
          successFn();
        });
      }
    },
    // 移交确认
    transferSure (obj) {
      const { personIds } = obj;
      transferSigning({
        orderFollowUserId: personIds,
        ids: this.isClickRow ? this.detailData.detail.id : this.getSelectionIds.join(',')
      }).then(res => {
        this.$message.success('移交成功');
        this.transferVisible = false;
        this.detailVisible = false;
        this.reloadTable();
      });
    },
    // 删除确认
    deleteSure () {
      if (this.checkShareData) {
        this.$message.error('选中数据有共享数据，无法删除');
        return;
      }
      delSigning({
        ids: this.isClickRow ? this.detailData.detail.id : this.getSelectionIds.join(',')
      }).then(res => {
        this.$message.success('删除成功');
        this.deleteVisible = false;
        this.detailVisible = false;
        this.reloadTable();
      });
    },
    // 新增签约
    handleAdd () {
      if (!getActState(this.$rootsList.usualRoots.ADD)) {
        this.$message.error('暂无权限');
        return;
      }
      this.visible = true;
      this.addSigningData = {};
      this.signIsEdit = false;
      // this.searchBoxDisabled = false;
      // 数据指标埋点
      this.$dataIndicatorBuryingPoint(23);
    },
    // 按钮的事件
    handleCommand (value) {
      const fn = this.btnList.find(i => i.value === value).clickFn;
      fn && fn(this);
    },
    handleRowClick (params) {
      // 当客户来源是信息流直推时(cstSource=130)时详情接口单独的
      if (Number(params.cstSource) === infoFlowCustomerType) {
        getInfoFlowOrderById({
          id: params.flowOrderId
        }).then(res => {
          this.customerBasicData = res;
        });
      }

      this.planData = { id: params.flowOrderId }; // 组件里面只需要一个客户id
      // 获取渠道成本对象
      this.chanelCostItemDta = { id: params.id, channelCostAmount: params.channelCostAmount, channelCostRemark: params.channelCostRemark };
      if (params.delFlag === 1) {
        this.$message.error('客户已被删除');
        return;
      }
      if (params.followUserId === 0) {
        this.$message.error('客户已被移入公海,请先领取');
        return;
      }
      this.processStatus = params.processStatus;
      getCustomerDetailById({ id: params.flowOrderId, desensitizationRange: 60 }).then(customerData => {
        this.customerData = customerData;
        // 当客户来源不是信息流直推时还是用之前的数据
        if (Number(params.cstSource) !== infoFlowCustomerType) {
          this.customerBasicData = customerData;
        }
        if (customerData.followUserId) { // followUserId===0 为公海用户
          // 获取成本项列表
          this.getCostList(params.id);
          this.isClickRow = true;
          this.detailData = {
            detail: params,
            title: customerData.realName, // 数据脱敏
            linkPhone: customerData.phone,
            desc: `tel: ${customerData.phone}`,
            defaultImg: 'customer.png',
            steps: [
              { title: '贷款金额（万）', content: params.loanMoney, width: '162px' },
              { title: '贷款期限（月）', content: params.loanTerm, width: '162px' },
              // {title: '贷款产品', content: this.selectProductList.filter(v => v.id === params.targetProductId)[0] ? this.selectProductList.filter(v => v.id === params.targetProductId)[0].productName : ''},
              { title: '贷款产品', content: params.productName, width: '162px' },
              { title: '五级分类', content: this.loanCategoryList.filter(v => v.value === params.loanCategory)[0] ? this.loanCategoryList.filter(v => v.value === params.loanCategory)[0].label : '-', width: '162px' },
              { title: '服务费', content: !this.basics.isNull(params.serviceRate) ? params.serviceRate : '-', width: '162px' },
              { title: '负责人', content: params.followUserName, width: '162px' }
            ],
            formInfo: [
              {
                title: '签约资料'
              },
              {
                title: '成本项'
              }
            ]
          };
          this.detailDisabled = !getActState(this.$rootsList.usualRoots.EDIT) && this.detailData.detail.shareFlag === '1';
          // 判断权限
          enterpriseCanViewOrder({ shopOrderId: params.flowOrderId, type: 1 }).then(res => {
            if (res && getToApply(this.$rootsList.menuePerms.SHOP_ORDER_MANAGER)) {
              this.detailData.formInfo = [
                {
                  title: '签约资料'
                },
                {
                  title: '成本项'
                },
                {
                  title: '基本资料'
                },
                {
                  title: '复印件'
                },
                {
                  title: '还款计划'
                }
              ];
            }
          });
          if (this.customFields && this.customFields.length) {
            this.customFields.forEach(v => {
              this.detailData.formInfo[0].formItems[0].children.push({ label: v.title, value: params[v.key], type: 'text' });
            });
          }
          Promise.all([getSubTableDataByBusiness({
            dataId: params.id,
            tableType: this.filterType
          }),
          getSignDetailApi({
            id: params.id
          })]).then(([subTableData, res]) => {
            this.subTableData = subTableData;
            this.addSigningData = res || {};
          }).finally(() => {
            this.detailVisible = true;
          });
        } else {
          this.$message.error('客户已被移入公海,请先领取');
        }
      });
    },
    changeTab (index) {
      this.channel_current = index;
      console.log(this.channel_current, index);
    },
    // 获取当前机构id
    getOrganId () {
      getOrganInfoApi({ userId: this.$store.getters.userInfo.id }).then(res => {
        console.log('res');
        this.$store.commit('SET_ORGANIZATION_INFO', res);
      });
    },
    // 表头单击
    tableHeaderFilter (column, event) {
      // 当有选择项时,不操作
      if (this.getSelectionLen > 0) {
        return;
      }
      setTimeout(() => {
        this.$refs.filterSearchDialog.showModal = true;
        this.$refs.filterSearchDialog.filterListIndex = 1;
        // column.property-可能出现列表显示productName,搜索使用productId导致字段不一致的情况
        // this.$refs.filterSearchDialog.getIndex(column.property);
        this.$refs.filterSearchDialog.getIndex(column.label);
      }, 0);
      this.className = 'center';
    },
    // 点击审批中的流程图标
    clickFlow (row) {
      getFlowDetailDataByBusiness({
        linkId: row.id,
        tableType: this.filterType
      }).then(flowDetailData => {
        this.flowDetailData = flowDetailData || {};
        this.flowDetailVisible = true;
      });
    },
    // 流程操作后
    flowSuccess () {
      this.reloadTable();
    },
    // 处理表格合计内容
    dealTableTotal (params, tableData = []) {
      polymerizationTableDataSign(params).then(res => {
        this.tableTotalList = computedCurrentPageTotal(res, tableData);
      });
    },
    handleShare () {
      shareDataList({
        tableType: this.filterType,
        linkId: this.detailData.detail.id
      }).then(res => {
        this.isShareDataList = res;
        this.shareVisible = true;
      });
    },
    handleShareSure (item) {
      const data = {
        tableType: this.filterType,
        linkId: this.detailData.detail.id,
        userIdStr: item.userIds.join()
      };
      shareDataSave(data).then(() => {
        this.$message.success('共享成功');
        this.shareVisible = false;
      });
    }
  },
  watch: {
    '$route.query.id': {
      handler () {
        if (!this.basics.isNull(this.$route.query.id) && !this.basics.isNull(this.$route.query.tab) && Number(this.$route.query.tab) === 0) {
          // this.clientId = '';
          this.refreshTable();
          setTimeout(() => {
            this.clientId = this.$route.query.id.split('_')[0];
            const msgType = this.$route.query.msgType;
            const data = {};
            if (msgType && Number(msgType) === 101) {
              data.idList = this.clientId;
              data.shared = true;
            } else {
              data.idList = this.clientId;
            }
            getSigningList(data).then(res => {
              console.log(res);
              const arr = res.datas;
              if (arr.length) {
                this.handleRowClick(arr[0]);
              } else {
                this.$message.error('当条数据已取消共享或被删除，已无法查看');
              }
            });
          });
        }
      },
      immediate: true
    }
  }
};
</script>

<style scoped lang="scss">
</style>
<style lang="scss">
@import "~@/styles/base-table-page.scss";
</style>
<style lang="scss" scoped>
.operates {
  display: flex;
  .operate-btn {
    margin-right: 10px;
    margin-left: 0;
  }
}
.cost-item-box {
  display: flex;
  height: 100%;
  padding: 0 16px;
  .tabs {
    margin-right: 16px;
    box-sizing: border-box;
    width: 150px;
    flex: 0 0 auto;
    > div {
      height: 40px;
      cursor: pointer;
      &.current {
        background: #f3f5fe;
      }
      padding: 0 16px;
      line-height: 40px;
    }
    background: #f8f8f8ff;
  }
  .box {
    flex: 1;
  }
  .add-cost {
    width: 100%;
    height: 38px;
    background: #f3f5fe;
    display: flex;
    align-items: center;
    justify-content: center;
    color: $primary-color;
    font-size: $font-size-small;
    cursor: pointer;
    em {
      margin-right: 6px;
    }
  }
}

/deep/ .form-content {
  height: 100%;
}

.contact-item {
  &.channel-item {
    border: none;
    background: #f9f9f9ff;
  }
  border-radius: 2px;
  border: 1px dashed #d2d2d2;
  margin-bottom: 20px;
  font-size: 13px;
  padding: 16px 16px 0;
  color: $main-text-color;
  position: relative;
  &:hover {
    .icon-edit {
      display: block;
    }
    .icon-xiugai2 {
      display: block;
    }
  }
  .icon-xiugai2 {
    position: absolute;
    top: 8px;
    right: 8px;
    display: none;
    cursor: pointer;
  }
  .icon-edit {
    position: absolute;
    top: 8px;
    right: 8px;
    display: none;
    cursor: pointer;
  }
  .col-item {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    .item-label {
      color: $secondary-text-color;
      font-size: 13px;
      margin-right: 5px;
      font-weight: 400;
    }
    .content {
      color: $main-text-color;
      font-size: 13px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}
</style>
